import { Injectable, inject } from '@angular/core';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';

import {Observable, of, throwError} from 'rxjs';
import { map, catchError } from 'rxjs/operators';

import {BYODCompletion, Customer, MyCustomer} from '../shared/interfaces';
import { EmailSmsCompletion } from '../shared/interfaces';
import { ApiUrlService } from './api-url.service';
import {myCustomer} from "../../assets/mock-data";

@Injectable({ providedIn: 'root' })
export class DataService {

  apiUrlService = inject(ApiUrlService);
  http = inject(HttpClient);

  // apiUrl = this.apiUrlService.getApiUrl();

  getCustomers11(): Observable<Customer[]> {
    return this.http.get<Customer[]>(this.apiUrl + 'customers')
      .pipe(
        map(data => {
          // Sort by name
          return data.sort((a: Customer, b: Customer) => {
            if (a.company < b.company) {
              return -1;
            }
            if (a.company > b.company) {
              return 1;
            }
            return 0;
          });
        }),
        catchError(this.handleError)
      );

  }

  private apiUrl = 'https://api.arounddeal.com/v2/people/search';

  // constructor(private http: HttpClient) { }

  getCustomers22(): Observable<Customer[]> {
    const headers = new HttpHeaders({
      'Content-Type': 'application/json'
    });

    const body = {
      "industry_id": ["48"],
      "country_code": ["kw"],
      "page": 1,
      "pageSize": 7
    };

    return this.http.post<Customer[]>(this.apiUrl, body, { headers })
      .pipe(
        map(data => {
          // Sort by company name
          return data.sort((a: Customer, b: Customer) => {
            if (a.company < b.company) {
              return -1;
            }
            if (a.company > b.company) {
              return 1;
            }
            return 0;
          });
        }),
        catchError(this.handleError)
      );
  }


  getCustomers(industry: string, country: string,page: number,  pageSize: number): Observable<any[]> {

    let mockData = myCustomer.data.list;
    //只回去前m到n个数据
    const start = page;
    const end = pageSize;
    mockData = mockData.slice(start, end);
    const data = mockData.map((item: any) =>  {
      const customer: any = {
        id: item.id,
        name_first: item.name_first,
        name_last: item.name_last,
        job_title: item.job_title,
        email_business: item.email_business,
        email: item.email_direct,
        company_name: item.company_name,
        phone: item.phone,
      };
      return customer;
    });

    // Sort by company name
    data.sort((a: Customer, b: Customer) => {
      if (a.company < b.company) {
          return -1;
      }
      if (a.company > b.company) {
          return 1;
      }
      return 0;
    });

    return of(data)

  }

  getCustomers1(): Observable<Customer[]> {
    const headers = new HttpHeaders({
      'Content-Type': 'application/json',
      'Authorization': 'Bearer AD_MLUL1yW2ZGSMz4q40BcCnpBzhPdzooSb'
    });

    const body = {
      "industry_id": ["48"],
      "country_code": ["kw"],
      "page": 1,
      "pageSize": 7
    };

    return this.http.post<MyCustomer>(this.apiUrl, body, { headers })
      .pipe(
        map(response => {
          const lala = response.data.list;
          // 假设返回的数据结构如下
          // { data: { results: Array<any> } }
          const data = lala.map((item: any) => {
            /*
            {
  "arounddeal_id": "v4hrdxoscw",
  "name_first": "Abdel Rahman",
  "name_last": "Ibdah",
  "name_full": "Abdel Rahman Ibdah",
  "job_title": "Service Manager",
  "email_business": "",
  "email_direct": "******@gmail.com",
  "arounddeal_company_id": "t9abgdgjwp",
  "company_name": "Volvo CAR Kuwait"
}
            * */
            // 将每个 item 转换为 Customer 对象
            const customer: any = {
              id: item.id,
              name_first: item.name_first,
              name_last: item.name_last,
              job_title: item.job_title,
              email_business: item.email_business,
              email: item.email_direct,
              company_name: item.company_name,
              phone: item.phone,
            };
            return customer;
          });

          // Sort by company name
          return data.sort((a: Customer, b: Customer) => {
            if (a.company < b.company) {
              return -1;
            }
            if (a.company > b.company) {
              return 1;
            }
            return 0;
          });
        }),
        catchError(this.handleError)
      );
  }

  getCustomersByFind(industry: string, country: string, page: number, pageSize: number): Observable<Customer[]> {
    const headers = new HttpHeaders({
      'Content-Type': 'application/json',
      'Authorization': 'Bearer AD_MLUL1yW2ZGSMz4q40BcCnpBzhPdzooSb'
    });

    const body = {
      "industry_id": [industry],
      "country_code": [country],
      "page": page,
      "pageSize": pageSize
    };

    return this.http.post<MyCustomer>(this.apiUrl, body, { headers })
        .pipe(
            map(response => {
              const lala = response.data.list;
              // 假设返回的数据结构如下
              // { data: { results: Array<any> } }
              const data = lala.map((item: any) => {

                // 将每个 item 转换为 Customer 对象
                const customer: any = {
                  id: item.id,
                  name_first: item.name_first,
                  name_last: item.name_last,
                  job_title: item.job_title,
                  email_business: item.email_business,
                  email: item.email_direct,
                  company_name: item.company_name,
                  phone: item.phone,
                };
                return customer;
              });

              // Sort by company name
              return data.sort((a: Customer, b: Customer) => {
                if (a.company < b.company) {
                  return -1;
                }
                if (a.company > b.company) {
                  return 1;
                }
                return 0;
              });
            }),
            catchError(this.handleError)
        );
  }

  getCustomer(id: number): Observable<Customer> {
    return this.http.get<Customer[]>(this.apiUrl + 'customers/' + id)
      .pipe(
        map(customers => {
          const customer = customers.filter((cust: Customer) => cust.id === id);
          return customer[0];
        }),
        catchError(this.handleError)
      );
  }

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  generateSql(prompt: string): Observable<any> {
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    return this.http.post<any>(this.apiUrl + 'generateSql', { prompt })
      .pipe(
        catchError(this.handleError)
      );
  }

  completeBYOD(prompt: string): Observable<string> {
    return this.http.post<string>(this.apiUrl + 'completeBYOD', { prompt })
      .pipe(
        catchError(this.handleError)
      );
  }

  completeEmailSmsMessages(prompt: string, company: string, contactName: string): Observable<EmailSmsCompletion> {
    return this.http.post<EmailSmsCompletion>(this.apiUrl + 'completeEmailSmsMessages', { prompt, company, contactName })
      .pipe(
        catchError(this.handleError)
      );
  }

  completeEmailSmsMessagesByApi3(prompt: string, company: string, contactName: string, language:string): Observable<EmailSmsCompletion> {
    const headers = new HttpHeaders({
      'Content-Type': 'application/json'
    });

    const body = {
      "user_input": "介绍下你自己，",
      "user": company,
      "language": language,
    };

    let url = "http://127.0.0.1:8000/api/get_chat_chain_Qwen/";

    return this.http.post<any>(url, body, { headers }).pipe(
        map(data => {
          // Assuming data contains the response with the email body
          let emailData: EmailSmsCompletion = {
            emailSubject: 'emailSubject', // This should be set appropriately based on your API response
            emailBody: data.data || 'emailBody aaa', // Assuming API returns emailBody
            error: data.error || 'error',
            sms: data.data || 'sms',
            status: data.status || true
          };
          return emailData;
        }),
        catchError(error => {
          console.error('Error fetching email data:', error);
          // Return a default value or handle the error as necessary
          let defaultEmailData: EmailSmsCompletion = {
            emailSubject: '',
            emailBody: '',
            error: 'Error occurred',
            sms: '',
            status: false
          };
          return of(defaultEmailData); // Return a default observable with error info
        })
    );
  }

  completeEmailSmsMessagesByApi2(prompt: string, company: string, contactName: string): Observable<EmailSmsCompletion> {
    console.log(prompt)
    let url = 'https://getmailcontent.ambitiousmeadow-9aaf9fa5.japaneast.azurecontainerapps.io/get_mail_content?prompt='+prompt;


    // return this.http.post<EmailSmsCompletion>(this.apiUrl + 'completeEmailSmsMessages', { prompt, company, contactName })
    //     .pipe(
    //         catchError(this.handleError)
    //     );

    return this.http.get<any>(url).pipe(
        map(data => {
          // Assuming data contains the response with the email body
          let emailData: EmailSmsCompletion = {
            emailSubject: 'emailSubject', // This should be set appropriately based on your API response
            emailBody: data.data || 'emailBody aaa', // Assuming API returns emailBody
            error: data.error || 'error',
            sms: data.sms || 'sms',
            status: data.status || true
          };
          return emailData;
        }),
        catchError(error => {
          console.error('Error fetching email data:', error);
          // Return a default value or handle the error as necessary
          let defaultEmailData: EmailSmsCompletion = {
            emailSubject: '',
            emailBody: '',
            error: 'Error occurred',
            sms: '',
            status: false
          };
          return of(defaultEmailData); // Return a default observable with error info
        })
    );
  }

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  filter(val: string, data: any[]) {
    if (val) {
      val = val.toLowerCase();
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      const filteredData = data.filter((data: any) => {
        for (const property in data) {
          const propValue = data ? data[property].toString().toLowerCase() : '';
          if (propValue && propValue.indexOf(val) > -1) {
            return true;
          }
        }
        return false;
      });
      return filteredData;
    } else {
      return null;
    }
  }

  private handleError(error: HttpErrorResponse) {
    console.error('server error:', error);
    if (error.error instanceof Error) {
      const errMessage = error.error.message;
      return throwError(() => errMessage);
      // Use the following instead if using lite-server
      // return Observable.throw(err.text() || 'backend server error');
    }
    return throwError(() => error || 'Node.js server error');
  }

  /*
  * const headers = new HttpHeaders({
      'Content-Type': 'application/json',
      'Authorization': 'Bearer AD_MLUL1yW2ZGSMz4q40BcCnpBzhPdzooSb'
    });

    const body = {
      "industry_id": ["48"],
      "country_code": ["kw"],
      "page": 1,
      "pageSize": 7
    };

    return this.http.post<MyCustomer>(this.apiUrl, body, { headers })*/
  getPromptByApi2(user:string, email:string, language:string, company:string): Observable<any> {
    const headers = new HttpHeaders({
      'Content-Type': 'application/json'
    });

    const body = {
      "user_input": "",
      "user": user,
      "email": email,
      "company": company,
      "language": language,
    };

    let url = "http://127.0.0.1:8000/api/get_chat_chain_Qwen_prompt/";

    return this.http.post<any>(url, body, { headers }).pipe(
        catchError(this.handleError)
    );
  }
  getPrompt(): Observable<any> {
    return this.http.get<any>(this.apiUrl);
  }

  getPromptByApi(): Observable<any> {
    return this.http.get<any>('https://getprompt.ambitiousmeadow-9aaf9fa5.japaneast.azurecontainerapps.io/get_prompt')
        .pipe(
            map(data => {
              // Sort by name
              return data}),
            catchError(this.handleError)
        );

  }
}
